use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::category_paths::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub category_id: String,
    pub path_id: String,
    pub level: i32,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Category ID must not be empty."))]
    pub category_id: String,
    #[validate(length(min = 1, message = "Path ID must not be empty."))]
    pub path_id: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            category_id: self.category_id.as_ref().to_owned(),
            path_id: self.path_id.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::category_paths::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a category path by the provided id
    ///
    /// # Errors
    ///
    /// When could not find category path or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let category_path = category_paths::Entity::find()
            .filter(
                model::query::condition()
                    .eq(category_paths::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        category_path.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds category paths by the provided category id
    ///
    /// # Errors
    ///
    /// When could not find category paths or DB query error
    pub async fn find_by_category_id(
        db: &DatabaseConnection,
        category_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let paths = category_paths::Entity::find()
            .filter(
                model::query::condition()
                    .eq(category_paths::Column::CategoryId, category_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(paths)
    }

    /// finds category paths by the provided path id
    ///
    /// # Errors
    ///
    /// When could not find category paths or DB query error
    pub async fn find_by_path_id(db: &DatabaseConnection, path_id: &str) -> ModelResult<Vec<Self>> {
        let paths = category_paths::Entity::find()
            .filter(
                model::query::condition()
                    .eq(category_paths::Column::PathId, path_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(paths)
    }

    /// finds category paths by the provided level
    ///
    /// # Errors
    ///
    /// When could not find category paths or DB query error
    pub async fn find_by_level(db: &DatabaseConnection, level: i32) -> ModelResult<Vec<Self>> {
        let paths = category_paths::Entity::find()
            .filter(
                model::query::condition()
                    .eq(category_paths::Column::Level, level)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(paths)
    }

    /// Asynchronously creates a category path and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the category path into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let category_path = category_paths::ActiveModel {
            category_id: ActiveValue::set(params.category_id.to_string()),
            path_id: ActiveValue::set(params.path_id.to_string()),
            level: ActiveValue::set(params.level),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(category_path)
    }
}

impl ActiveModel {
    /// Updates the category path's level
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_level(mut self, db: &DatabaseConnection, level: i32) -> ModelResult<Model> {
        self.level = ActiveValue::set(level);
        Ok(self.update(db).await?)
    }
}
